/** ***********************************************
 * CodeGen
 *
 * @author  Jonnie Spratley
 * @date 3/05/2009
 * @licence MCIYC
 * @website http://jonniespratley.com/code
 * @contact jonniespratley@gmail.com
 *********************************************** */
package com.jonniespratley.codegen.commands
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.serialization.json.JSON;
	import com.jonniespratley.codegen.business.CodeGenDelegate;
	import com.jonniespratley.codegen.events.CallClassFunctionEvent;
	import com.jonniespratley.codegen.model.ModelLocator;
	import com.jonniespratley.codegen.vo.*;

	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.utils.ObjectUtil;


	public class CallClassFunctionCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		public function execute( event:CairngormEvent ) : void
		{
			var evt:CallClassFunctionEvent = event as CallClassFunctionEvent;
			var delegate:CodeGenDelegate = new CodeGenDelegate( this );
				delegate.callClassFunction( evt.aClassPath, evt.aClassFunction, evt.aClassArgs );
		}

		public function result( data:Object ) : void
		{
			var resultObj:ResultEvent = data as ResultEvent;
			var rawData:String = String( resultObj.result );

			if ( resultObj.result is String )
			{
				var jsonArray:Array = ( JSON.decode( rawData ) as Array );
				var tempAC:ArrayCollection = new ArrayCollection( jsonArray );

				model.inspectedClassCollection = tempAC;
			}
			trace( ObjectUtil.toString( resultObj.result ) );
			ModelLocator.getInstance().applicationDump += ObjectUtil.toString( resultObj.result );
		}

		public function fault( fault:Object ):void
		{
			var faultEvt:FaultEvent = fault as FaultEvent;
			//Alert.show(faultEvt.fault.toString(), "Service Error");
			trace(faultEvt.fault.faultString);
		}

	}
}
